package builder.trainer.data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class DataManager {

	private List<String[]> records = new ArrayList<String[]>();
	private List<String[]> mixedRecords = new ArrayList<String[]>();
	private String[] attrNames = null;
	private String dataFile;

	public DataManager(String[] attrNames,List<String[]> records){
		this.records = records;
		this.attrNames = attrNames;
	}
	
	public DataManager(String dataFile) {
		this.dataFile = dataFile;
		this.readFile();
	}

	private void readFile() {
		File file = new File(dataFile);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;

			tempString = reader.readLine();
			this.attrNames = (tempString.trim().split("\\s*#\\s*"));
			
			while ((tempString = reader.readLine()) != null) {
				String[] strs = tempString.trim().split("\\s*,\\s*");
				getRecords().add(strs);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}
	
	public List<String[]> mixUp() {
		this.mixedRecords.clear();
		LinkedList<String[]> lRecords = this.toLinkedList(records);
		Random r = new Random();
		int count = lRecords.size();
		for (int i = 0; i < count; i++) {
			int index = r.nextInt(lRecords.size());
			mixedRecords.add(lRecords.remove(index));
		}
		return mixedRecords;
	}
	
	public ArrayList<String[]> mixUp(ArrayList<String[]> records) {
		LinkedList<String[]> lRecords = this.toLinkedList(records);
		ArrayList<String[]> mixedRecords = new ArrayList<String[]>();
		Random r = new Random();
		for (int i = 0; i < lRecords.size(); i++) {
			int index = r.nextInt(records.size());
			mixedRecords.add(lRecords.remove(index));
		}
		return mixedRecords;
	}

	private LinkedList<String[]> toLinkedList(List<String[]> records) {
		LinkedList<String[]> lRecords = new LinkedList<String[]>();
		for (String[] record : records) {
			lRecords.add(record);
		}
		return lRecords;
	}

	public List<String[]> getMixedRecords() {
		return mixedRecords;
	}
	
	public List<String[]> getRecords() {
		return records;
	}

	public String[] getAttrNames() {
		return attrNames;
	}
}
